/**
 * 添加拦截器
 * 1 拦截request
 * 2 拦截 uploadFile
 * */

import {
	config
} from '@/common/config.js'
import store from '@/store/index.js'
const httpInterceptor = {
	invoke (options) {
		// 1 连接基础路径
		if (!options.url.startsWith('http')) {
			options.url = config.baseUrl + options.url
		}
		// 2 设置请求超时时间
		options.timeout = config.loadingTime
		const token = store.state.token ?? ''
		options.header = {
			...options.header,
			'Authorization': token,
		}
		// 固定添加参数
		if (options.custid) {
			options.data = {
				...options.data,
				custid: store.state.isExternal ? (store.state.custid ?? '') : '',
			}
		} else if (options.userid) {
			options.data = {
				...options.data,
				userid: store.state.userid ?? '',
			}
		}
	},
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

export const http = (options = {}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success: (res) => {
				const { code, msg } = res.data
				if (res.statusCode === 200) {
					if (code === 200 || code === 0) {
						resolve(res.data)
					} else if (code === 401) {
						store.commit('quitLogin')
					} else {
						// 传入是否提示错误
						if (!options.data?.isTotal) {
							uni.$u.toast(msg || '请求失败')
						}
						reject(res.data)
					}
				} else {
					reject(res.data)
				}
			},
			fail: (err) => {
				reject(err)
			},
		})
	})
}